<template>
  <ElementDialog
    ref="dialog"
    class="import-dialog"
    :title="dlgTitle"
    :visible="visible"
    embed
    center
    top="20vh"
    :width="showDownloadTemplate ? '750px' : '550px'">
    <ElForm ref="form" :model="form">
      <ElFormItem
        label="选择导入文件"
        prop="fileList"
        :rules="[{ required: true, message: '请选择导入文件' }]"
        style="padding-top: 0">
        <ElUpload
          ref="upload"
          :accept="fileAccept"
          :headers="getHeader()"
          class="upload-demo"
          :action="importAction"
          :auto-upload="false"
          :on-change="handleChange"
          :on-error="onError"
          :on-success="handleAvatarSuccess"
          :file-list="fileList">
          <ElButton size="small" type="primary">点击上传导入文件</ElButton>
        </ElUpload>
      </ElFormItem>
      <div v-if="showDownloadTemplate" class="upload-tips">
        说明：请按指定的Excel模板导入数据，{{
          subDlgTitle ? subDlgTitle : dlgTitle
        }}的模板可通过下方按钮【下载模板】进行下载。(建议采用xlsx文件导入)
      </div>
      <div v-else class="upload-tips">说明：请按指定的模板导入数据，建议采用xls格式文件导入。</div>
      <!--<div class="error-message" v-if="errorMessageList.length !== 0">-->
      <!--  <div class="error-message-item" v-for="(item, index) in errorMessageList" :key="`msg${index}`">-->
      <!--    第{{ item.sheetNo + 1 }}个页签第{{ item.row + 1 }}行第{{ item.col + 1 }}列 {{ item.errorMsg }}-->
      <!--  </div>-->
      <!--</div>-->
    </ElForm>
    <template #footer>
      <ElButton v-if="showDownloadTemplate" type="primary" size="small" @click="downloadBtn">下载模版</ElButton>
      <ElButton type="primary" size="small" @click="submitForm">导入</ElButton>
      <ElButton size="small" @click="() => $refs.dialog.hide()">取消</ElButton>
    </template>
  </ElementDialog>
</template>

<script>
  import { getHeader } from '@/api/attachment/attachment'
  import { delay, formatSize, getFileSuffix } from '@web-utils/core'

  function newFile(file) {
    return {
      id: file.uid,
      fileType: getFileSuffix(file.name),
      fileName: file.name,
      status: 'loading',
      percentage: 0,
      fileSize: file.size
    }
  }

  export default {
    name: 'ImportDialog',
    props: {
      visible: Boolean,
      dlgTitle: String,
      subDlgTitle: String,
      viewId: String,
      // importApi: [Function, String],
      importAction: String,
      importTask: Function,
      downloadTplApi: Function,
      limitSize: {
        type: Number,
        default: 10 * 1024 * 1024
      },
      serviceItemOption: {
        type: Array,
        default: () => []
      },
      // 是否显示下载模板按钮
      showDownloadTemplate: {
        type: Boolean,
        default: true
      },
      // 文件上传类型
      fileAccept: {
        type: String,
        default: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'
      }
    },
    data() {
      return {
        loading: null,
        form: {
          serviceItem: this.serviceItemOption[0]?.code || '',
          fileList: []
        },
        fileList: [],
        errorMessageList: []
      }
    },
    watch: {
      visible: {
        immediate: true,
        async handler() {
          await this.$emit('get-serviceItem', this.serviceItemOption[0]?.code || '')
        }
      }
    },
    methods: {
      getHeader,
      submitForm() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            await this.$refs.upload.submit()
            this.loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            this.$refs.dialog.hide()
          }
        })
      },
      async beforeUploadFile(file) {
        if (file.size > this.limitSize) {
          const message = `上传文件不能超过 ${formatSize(this.limitSize)}！`
          this.$message.error(`上传文件不能超过 ${formatSize(this.limitSize)}！`)
          return Promise.reject(new Error(message))
        }
        this.fileList.push(newFile(file))
        await this.fetchUnId()
      },
      async changServiceItem(value) {
        this.fileList = []
        this.form.fileList = []
        await this.$emit('get-serviceItem', value)
      },
      async downloadBtn() {
        if (this.downloadTplApi) {
          await this.downloadTplApi()
        }
      },
      async onError(res) {
        const err = JSON.parse(res.message)
        this.loading.close()
        this.$message.error(err.message || '系统异常，请联系管理员')
      },
      async handleAvatarSuccess(res) {
        if (res.code === 0) {
          this.$emit('import-success', res.data)
          this.close()
          // await this.$message.success('文件上传成功')
          // if (res.data?.unid) {
          //   this.loading = this.$loading({
          //     lock: true,
          //     text: 'Loading',
          //     spinner: 'el-icon-loading',
          //     background: 'rgba(0, 0, 0, 0.7)'
          //   })
          //   await this.getImportTask(res.data.unid)
          // }
          // await this.$importSuccess(this.viewId)
          this.loading.close()
          await this.$message.success('导入成功')
          await this.$reloadTableView(this.viewId)
        } else {
          this.loading.close()
          await this.$message.error(res.message || '文件上传失败')
          this.fileList = []
          this.form.fileList = []
        }
      },
      async getImportTask(unid) {
        const res = await this.importTask(unid)
        if (res.data?.status === 3) {
          this.loading.close()
          await this.$message.success('导入成功')
          this.errorMessageList = res.data.result || []
        } else {
          await delay(5000)
          await this.getImportTask(unid)
        }
      },
      async handleChange(file, fileList) {
        if (!['application/vnd.ms-excel', ...this.fileAccept.split(',')].includes(file.raw.type)) {
          fileList.pop()
          if (this.showDownloadTemplate) this.$message.info('您导入的文件格式不正确，请下载模板')
          else this.$message.info('您导入的文件格式不正确，请检查')
        } else {
          this.form.fileList = fileList
          await this.$nextTick()
          this.$refs.form && this.$refs.form.clearValidate('fileList')
        }
      }
    }
  }
</script>

<!--suppress Stylelint -->
<style lang="scss">
  .import-dialog {
    .dialog-footer {
      text-align: end;
    }

    .upload-tips {
      font-size: 14px;
      line-height: 20px;
    }

    .error-message {
      .error-message-item {
        padding: 3px 10px;
        color: #f56c6c;
      }
    }

    .el-form {
      text-align: left;

      .el-form-item__label {
        height: 36px;
        padding-top: 0;
        line-height: 36px;
      }
    }
  }
</style>
